package at.irian.jsfatwork.broker.web.aop;

import at.irian.jsfatwork.broker.domain.DomainModelException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 * @author Thomas Spiegl, IRIAN Solutions GmbH
 */
@Aspect
@Order(value = 0)
public class ExceptionInterceptor {

    private Logger logger = LoggerFactory.getLogger(ExceptionInterceptor.class);

    @Around("execution(public * at.irian.jsfatwork.broker.web.model.*.*(..))")
    public Object checkForValidationException(ProceedingJoinPoint pjp) throws Throwable {
        try {
            return pjp.proceed();
        } catch (DomainModelException e) {

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
            return null;

        } catch (Exception e) {  // catch all Excptions

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("System error: " + e.getMessage()));
            logger.error("Internal system error", e);
            return null;
        }
    }
}
